/**
 * 大屏适配工具类
 * 提供多种适配策略和辅助工具
 */
export class ScreenAdapter {
  constructor(options = {}) {
    this.options = {
      designWidth: 1920,
      designHeight: 1080,
      mode: "scale", // scale | fit | full | rem
      remBase: 16,
      maxScale: 3,
      minScale: 0.3,
      ...options,
    };

    this.callbacks = [];
    this.isInitialized = false;
  }

  /**
   * 获取当前窗口尺寸
   */
  getWindowSize() {
    return {
      width: window.innerWidth || document.documentElement.clientWidth,
      height: window.innerHeight || document.documentElement.clientHeight,
    };
  }

  /**
   * 计算缩放比例
   */
  calculateScale(windowWidth, windowHeight) {
    const { designWidth, designHeight, mode, maxScale, minScale } = this.options;

    const scaleX = windowWidth / designWidth;
    const scaleY = windowHeight / designHeight;

    let finalScaleX, finalScaleY;

    switch (mode) {
      case "fit":
        // 等比缩放，保证完全显示
        const minScale_fit = Math.min(scaleX, scaleY);
        finalScaleX = finalScaleY = Math.max(minScale, Math.min(maxScale, minScale_fit));
        break;
      case "full":
        // 填满屏幕，可能会裁剪
        const maxScale_full = Math.max(scaleX, scaleY);
        finalScaleX = finalScaleY = Math.max(minScale, Math.min(maxScale, maxScale_full));
        break;
      case "rem":
        // 基于rem的响应式适配
        const remScale = Math.min(scaleX, scaleY);
        this.setRootFontSize(remScale);
        finalScaleX = finalScaleY = 1;
        break;
      case "scale":
      default:
        // 自由缩放
        finalScaleX = Math.max(minScale, Math.min(maxScale, scaleX));
        finalScaleY = Math.max(minScale, Math.min(maxScale, scaleY));
        break;
    }

    return {
      scaleX: finalScaleX,
      scaleY: finalScaleY,
      ratio: Math.min(finalScaleX, finalScaleY),
      originalScaleX: scaleX,
      originalScaleY: scaleY,
    };
  }

  /**
   * 设置根字体大小（rem适配）
   */
  setRootFontSize(scale) {
    const { remBase } = this.options;
    const fontSize = remBase * scale;
    document.documentElement.style.fontSize = `${fontSize}px`;
  }

  /**
   * 获取适配样式
   */
  getAdaptStyle(customOptions = {}) {
    const windowSize = this.getWindowSize();
    const options = { ...this.options, ...customOptions };
    const scaleInfo = this.calculateScale(windowSize.width, windowSize.height);

    const style = {
      width: `${options.designWidth}px`,
      height: `${options.designHeight}px`,
      transformOrigin: "0 0",
      position: "fixed",
      left: "50%",
      top: "50%",
    };

    if (options.mode !== "rem") {
      style.transform = `scale(${scaleInfo.scaleX}, ${scaleInfo.scaleY}) translate(-50%, -50%)`;
    } else {
      style.transform = "translate(-50%, -50%)";
    }

    return {
      style,
      scaleInfo: {
        ...scaleInfo,
        windowWidth: windowSize.width,
        windowHeight: windowSize.height,
        mode: options.mode,
      },
    };
  }

  /**
   * 注册回调函数
   */
  onResize(callback) {
    if (typeof callback === "function") {
      this.callbacks.push(callback);
    }
  }

  /**
   * 移除回调函数
   */
  offResize(callback) {
    const index = this.callbacks.indexOf(callback);
    if (index > -1) {
      this.callbacks.splice(index, 1);
    }
  }

  /**
   * 触发回调
   */
  triggerCallbacks(data) {
    this.callbacks.forEach((callback) => {
      try {
        callback(data);
      } catch (error) {
        console.error("适配回调执行失败:", error);
      }
    });
  }

  /**
   * 初始化
   */
  init() {
    if (this.isInitialized) return;

    // 创建防抖函数
    this.debouncedResize = this.debounce(() => {
      const adaptData = this.getAdaptStyle();
      this.triggerCallbacks(adaptData);
    }, 100);

    // 监听事件
    window.addEventListener("resize", this.debouncedResize);
    window.addEventListener("orientationchange", this.debouncedResize);

    // 初始化执行
    const initialData = this.getAdaptStyle();
    this.triggerCallbacks(initialData);

    this.isInitialized = true;
    console.log("ScreenAdapter 初始化完成");
  }

  /**
   * 销毁
   */
  destroy() {
    if (!this.isInitialized) return;

    window.removeEventListener("resize", this.debouncedResize);
    window.removeEventListener("orientationchange", this.debouncedResize);

    this.callbacks = [];
    this.isInitialized = false;

    // 重置根字体大小
    if (this.options.mode === "rem") {
      document.documentElement.style.fontSize = "";
    }

    console.log("ScreenAdapter 已销毁");
  }

  /**
   * 防抖函数
   */
  debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  /**
   * 更新配置
   */
  updateOptions(newOptions) {
    this.options = { ...this.options, ...newOptions };
    if (this.isInitialized) {
      const adaptData = this.getAdaptStyle();
      this.triggerCallbacks(adaptData);
    }
  }

  /**
   * 获取当前缩放信息
   */
  getCurrentScale() {
    return this.getAdaptStyle();
  }
}

/**
 * 单例模式的全局适配器
 */
export const globalScreenAdapter = new ScreenAdapter();

/**
 * Vue 插件
 */
export const ScreenAdapterPlugin = {
  install(Vue, options = {}) {
    const adapter = new ScreenAdapter(options);

    Vue.prototype.$screenAdapter = adapter;
    Vue.prototype.$adaptToScreen = function (callback) {
      adapter.onResize(callback);
    };

    // 提供响应式的适配数据
    Vue.mixin({
      data() {
        return {
          $screenAdaptData: null,
        };
      },
      mounted() {
        if (this.$options.enableScreenAdapt) {
          this.$screenAdapter.onResize((data) => {
            this.$screenAdaptData = data;
          });
          this.$screenAdapter.init();
        }
      },
      beforeDestroy() {
        if (this.$options.enableScreenAdapt) {
          this.$screenAdapter.destroy();
        }
      },
    });
  },
};

/**
 * CSS适配工具函数
 */
export const screenUtils = {
  /**
   * 将设计稿px转换为相对单位
   */
  px2vw(px, designWidth = 1920) {
    return (px / designWidth) * 100 + "vw";
  },

  px2vh(px, designHeight = 1080) {
    return (px / designHeight) * 100 + "vh";
  },

  /**
   * 计算字体缩放
   */
  scaleFontSize(fontSize, scale) {
    return Math.max(12, fontSize * scale) + "px";
  },

  /**
   * 获取当前设备类型
   */
  getDeviceType() {
    const width = window.innerWidth;
    if (width < 768) return "mobile";
    if (width < 1024) return "tablet";
    if (width < 1920) return "desktop";
    return "large-screen";
  },

  /**
   * 检测是否为横屏
   */
  isLandscape() {
    return window.innerWidth > window.innerHeight;
  },

  /**
   * 检测设备像素比
   */
  getPixelRatio() {
    return window.devicePixelRatio || 1;
  },
};

/**
 * 大屏组件 Hook（Vue 3 Composition API 风格）
 */
export function useScreenAdapter(options = {}) {
  const adapter = new ScreenAdapter(options);

  const adaptData = ref(null);
  const isReady = ref(false);

  const init = () => {
    adapter.onResize((data) => {
      adaptData.value = data;
      if (!isReady.value) {
        isReady.value = true;
      }
    });
    adapter.init();
  };

  const destroy = () => {
    adapter.destroy();
  };

  const updateMode = (mode) => {
    adapter.updateOptions({ mode });
  };

  // 自动清理
  onBeforeUnmount(() => {
    destroy();
  });

  return {
    adaptData: readonly(adaptData),
    isReady: readonly(isReady),
    init,
    destroy,
    updateMode,
    adapter,
  };
}

export default ScreenAdapter;
